package com.wbxqy.car_management_system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wbxqy.car_management_system.entity.Car;
import com.wbxqy.car_management_system.entity.CarRequest;
import com.wbxqy.car_management_system.entity.Trip;
import com.wbxqy.car_management_system.entity.User;
import com.wbxqy.car_management_system.service.ICarRequestService;
import com.wbxqy.car_management_system.service.ICarService;
import com.wbxqy.car_management_system.service.ITripService;
import com.wbxqy.car_management_system.service.IUserService;
import com.wbxqy.car_management_system.utils.JwtTokenUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用车申请表 前端控制器
 *
 * @author wbxqy
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/wbxqy/carRequest")
public class CarRequestController {
    private static final Logger log = LoggerFactory.getLogger(CarRequestController.class);
    @Autowired
    private ICarRequestService carRequestService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ICarService carService;
    @Autowired
    private ITripService tripService;


    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param userId
     * @param carId
     * @param driverId
     * @param status
     * @return
     */
    @GetMapping("/page")
    public Page<CarRequest> getAllCarRequestsPage(@RequestParam(required = false, defaultValue = "1") Integer page,
                                                  @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                  @RequestParam(required = false) Integer userId,
                                                  @RequestParam(required = false) Integer carId,
                                                  @RequestParam(required = false) Integer driverId,
                                                  @RequestParam(required = false) String status) {
        // 构造分页构造器
        Page<CarRequest> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<CarRequest> queryWrapper = new QueryWrapper<>();

        // 添加过滤条件
        if (userId != null) {
            queryWrapper.eq("user_id_wbxqy", userId);
        }
        if (carId != null) {
            queryWrapper.eq("car_id_wbxqy", carId);
        }
        if (driverId != null) {
            queryWrapper.eq("driver_id_wbxqy", driverId);
        }
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status_wbxqy", status);
        }
        queryWrapper.orderByDesc("update_time_wbxqy");
        // 执行分页查询
        Page<CarRequest> carRequestPage = carRequestService.page(pageInfo, queryWrapper);
        List<CarRequest> carRequestList = new ArrayList<>();

        for (CarRequest carRequest : carRequestPage.getRecords()) {
            User user = null;
            Car car = null;
            User driver = null;

            if (carRequest.getUserIdWbxqy() != null) {
                user = userService.getById(carRequest.getUserIdWbxqy());
            }
            if (carRequest.getCarIdWbxqy() != null) {
                car = carService.getById(carRequest.getCarIdWbxqy());
            }
            if (carRequest.getDriverIdWbxqy() != null) {
                driver = userService.getById(carRequest.getDriverIdWbxqy());
            }
            carRequest.setUser(user);
            carRequest.setCar(car);
            carRequest.setDriver(driver);
            carRequestList.add(carRequest);
        }

        Page<CarRequest> resultPage = new Page<>(carRequestPage.getCurrent(), carRequestPage.getSize(), carRequestPage.getTotal());
        resultPage.setRecords(carRequestList);

        return pageInfo;

    }

    /**
     * 分页02-二审界面
     *
     * @param page
     * @param pageSize
     * @param userId
     * @param carId
     * @param driverId
     * @return
     */
    @GetMapping("/page_two")
    public Page<CarRequest> getAllCarRequestsPageTwo(@RequestParam(required = false, defaultValue = "1") Integer page,
                                                     @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                     @RequestParam(required = false) Integer userId,
                                                     @RequestParam(required = false) Integer carId,
                                                     @RequestParam(required = false) Integer driverId) {
        // 构造分页构造器
        Page<CarRequest> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<CarRequest> queryWrapper = new QueryWrapper<>();

        // 添加过滤条件
        if (userId != null) {
            queryWrapper.eq("user_id_wbxqy", userId);
        }
        if (carId != null) {
            queryWrapper.eq("car_id_wbxqy", carId);
        }
        if (driverId != null) {
            queryWrapper.eq("driver_id_wbxqy", driverId);
        }
        queryWrapper.eq("status_wbxqy", "S1_A").or().eq("status_wbxqy", "S2_A");
        queryWrapper.orderByDesc("update_time_wbxqy");
        // 执行分页查询
        Page<CarRequest> carRequestPage = carRequestService.page(pageInfo, queryWrapper);
        List<CarRequest> carRequestList = new ArrayList<>();

        for (CarRequest carRequest : carRequestPage.getRecords()) {
            User user = null;
            Car car = null;
            User driver = null;

            if (carRequest.getUserIdWbxqy() != null) {
                user = userService.getById(carRequest.getUserIdWbxqy());
            }
            if (carRequest.getCarIdWbxqy() != null) {
                car = carService.getById(carRequest.getCarIdWbxqy());
            }
            if (carRequest.getDriverIdWbxqy() != null) {
                driver = userService.getById(carRequest.getDriverIdWbxqy());
            }
            carRequest.setUser(user);
            carRequest.setCar(car);
            carRequest.setDriver(driver);
            carRequestList.add(carRequest);
        }

        Page<CarRequest> resultPage = new Page<>(carRequestPage.getCurrent(), carRequestPage.getSize(), carRequestPage.getTotal());
        resultPage.setRecords(carRequestList);

        return pageInfo;

    }

    /**
     * 列出当前用户的用车申请
     *
     * @param token
     * @param carId
     * @param driverId
     * @param status
     * @return
     */
    @GetMapping("/list-car-requests")
    public List<CarRequest> listCarRequests(@RequestHeader("Authorization") String token,
                                            @RequestParam(required = false) Integer carId,
                                            @RequestParam(required = false) Integer driverId,
                                            @RequestParam(required = false) String status) {
        // 根据 token 获取用户信息
        final User user = getUser(token);
        Integer userId = user.getUserIdWbxqy(); // 假设 User 对象有 getId() 方法

        QueryWrapper<CarRequest> queryWrapper = new QueryWrapper<>();

        // 添加过滤条件
        queryWrapper.eq("user_id_wbxqy", userId);
        if (carId != null) {
            queryWrapper.eq("car_id_wbxqy", carId);
        }
        if (driverId != null) {
            queryWrapper.eq("driver_id_wbxqy", driverId);
        }
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status_wbxqy", status);
        }

        // 执行查询
        List<CarRequest> carRequestList = carRequestService.list(queryWrapper);
        List<CarRequest> result = new ArrayList<>();

        for (CarRequest carRequest : carRequestList) {
            User requestUser = null;
            Car car = null;
            User driver = null;

            if (carRequest.getUserIdWbxqy() != null) {
                requestUser = userService.getById(carRequest.getUserIdWbxqy());
            }
            if (carRequest.getCarIdWbxqy() != null) {
                car = carService.getById(carRequest.getCarIdWbxqy());
            }
            if (carRequest.getDriverIdWbxqy() != null) {
                driver = userService.getById(carRequest.getDriverIdWbxqy());
            }
            carRequest.setUser(requestUser);
            carRequest.setCar(car);
            carRequest.setDriver(driver);
            result.add(carRequest);
        }

        return result;
    }

    /**
     * 列出当前司机的用车申请
     *
     * @param token
     * @return
     */
    @GetMapping("/list-car-driver")
    public List<CarRequest> listCarRequestsDriver(@RequestHeader("Authorization") String token) {
        // 根据 token 获取用户信息
        final User user = getUser(token);
        Integer userId = user.getUserIdWbxqy(); // 假设 User 对象有 getId() 方法
        System.out.println(userId);
        QueryWrapper<CarRequest> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_id_wbxqy", userId);
        // 执行查询
        List<CarRequest> carRequestList = carRequestService.list(queryWrapper);
        List<CarRequest> result = new ArrayList<>();
        for (CarRequest carRequest : carRequestList) {
            User requestUser = null;
            Car car = null;
            User driver = null;

            if (carRequest.getUserIdWbxqy() != null) {
                requestUser = userService.getById(carRequest.getUserIdWbxqy());
            }
            if (carRequest.getCarIdWbxqy() != null) {
                car = carService.getById(carRequest.getCarIdWbxqy());
            }
            if (carRequest.getDriverIdWbxqy() != null) {
                driver = userService.getById(carRequest.getDriverIdWbxqy());
            }
            carRequest.setUser(requestUser);
            carRequest.setCar(car);
            carRequest.setDriver(driver);
            result.add(carRequest);
        }

        return result;
    }

    /**
     * 获取当前carRequest详情
     *
     * @param token
     * @return
     */
    @GetMapping("/current_car-request")
    public CarRequest getCurrentCarRequest(@RequestHeader("Authorization") String token) {
        final User user = getUser(token);
        Integer userId = user.getUserIdWbxqy(); // 假设 User 对象有 getId() 方法

        QueryWrapper<CarRequest> queryWrapper = new QueryWrapper<>();

        // 添加过滤条件，确保 status_wbxqy 的条件被括号包裹
        queryWrapper.eq("user_id_wbxqy", userId)
                .and(wrapper -> wrapper.eq("status_wbxqy", "A")
                        .or().eq("status_wbxqy", "S")
                        .or().eq("status_wbxqy", "S1_A")
                        .or().eq("status_wbxqy", "S2_A"));
        final CarRequest one = carRequestService.getOne(queryWrapper);
        if (one == null) {
            return null;
        }
        return carRequestService.getFullRequest(one.getRequestIdWbxqy());
    }


    /**
     * 申请用车
     *
     * @param CarRequest
     * @return
     */
    @PostMapping("/apply")
    public ResponseEntity<?> applyForCar(@RequestHeader("Authorization") String token, @RequestBody CarRequest CarRequest) {
        CarRequest carRequest = new CarRequest();
        // 用户Id,token获取
        final User user = getUser(token);
        carRequest.setUserIdWbxqy(user.getUserIdWbxqy());
        // 申请时间,自动记录
        carRequest.setRequestDateWbxqy(LocalDate.now());
        // 用车开始时间
        carRequest.setStartTimeWbxqy(CarRequest.getStartTimeWbxqy());
        // 用车结束时间
        carRequest.setEndTimeWbxqy(CarRequest.getEndTimeWbxqy());
        carRequest.setStatusWbxqy("S"); // 待审核
        // 用车目的
        carRequest.setPurposeWbxqy(CarRequest.getPurposeWbxqy());
        carRequest.setCreateTimeWbxqy(LocalDateTime.now());

        carRequestService.save(carRequest);

        return ResponseEntity.ok("Car request submitted successfully");
    }

    /**
     * 结束用车
     *
     * @param token
     * @return
     */
    @PutMapping("/end")
    public ResponseEntity<?> endCarRequest(@RequestHeader("Authorization") String token) {
        final User user = getUser(token);
        Integer userId = user.getUserIdWbxqy(); // 假设 User 对象有 getId() 方法
        System.out.println(user.getUserIdWbxqy());
        QueryWrapper<CarRequest> queryWrapper = new QueryWrapper<>();

        // 添加过滤条件
        queryWrapper.eq("user_id_wbxqy", userId);
        queryWrapper.eq("status_wbxqy", "A")
                .or().eq("status_wbxqy", "S")
                .or().eq("status_wbxqy", "S1_A")
                .or().eq("status_wbxqy", "S2_A");
        // 获取到用车申请
        final CarRequest one = carRequestService.getOne(queryWrapper);
        if (one == null) {
            return ResponseEntity.ok("该用户没有进行中的用车");
        }
        // 设置用车申请结束
        one.setStatusWbxqy("E");
        carRequestService.updateById(one);
        // 解除司机占用
        final User driver = userService.getById(one.getDriverIdWbxqy());
        if (driver.getStatusWbxqy() != null && driver.getStatusWbxqy().equals("I")) {
            driver.setStatusWbxqy("N");
            userService.updateById(user);
        }
        return ResponseEntity.ok("结束用车申请");
    }


    /**
     * 分配用车
     *
     * @param carRequestDto
     * @return
     */
    @PutMapping("/agree_one")
    public ResponseEntity<?> approveCarRequestOne(@RequestHeader("Authorization") String token, @RequestBody CarRequest carRequestDto) {
        CarRequest carRequest = carRequestService.getById(carRequestDto.getRequestIdWbxqy());
        if (carRequest == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("没有对应的用车申请");
        }
        // 设置用车申请相关属性
        carRequest.setCarIdWbxqy(carRequestDto.getCarIdWbxqy());
        carRequest.setDriverIdWbxqy(carRequestDto.getDriverIdWbxqy());
        carRequest.setStatusWbxqy("S1_A"); // 初审-已分配
        carRequest.setUpdateTimeWbxqy(LocalDateTime.now());
        final User manager = getUser(token);
        carRequest.setPlanIdWbxqy(manager.getUserIdWbxqy());
        carRequest.setPlanTimeWbxqy(LocalDateTime.now());
        carRequestService.updateById(carRequest);
        // 设置司机被占用
        final User user = userService.getById(carRequest.getDriverIdWbxqy());
        user.setCarIdWbxqy(carRequestDto.getCarIdWbxqy());
        user.setStatusWbxqy("I");
        userService.updateById(user);
        return ResponseEntity.ok("通过");
    }

    /**
     * 确认分配无误
     *
     * @param carRequestDto
     * @return
     */
    @PutMapping("/agree_two")
    public ResponseEntity<?> approveCarRequestTwo(@RequestHeader("Authorization") String token, @RequestBody CarRequest carRequestDto) {
        CarRequest carRequest = carRequestService.getById(carRequestDto.getRequestIdWbxqy());
        if (carRequest == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("没有对应的用车申请");
        }
        // 设置用车申请相关属性
        carRequest.setStatusWbxqy("S2_A"); // 二审-已确认
        carRequest.setUpdateTimeWbxqy(LocalDateTime.now());
        carRequest.setPassTimeWbxqy(LocalDateTime.now());
        final User manager = getUser(token);
        carRequest.setPlanIdWbxqy(manager.getUserIdWbxqy());
        carRequest.setPlanTimeWbxqy(LocalDateTime.now());
        carRequestService.updateById(carRequest);
        return ResponseEntity.ok("通过");
    }

    /**
     * 审核通过
     *
     * @param approvalUrlWbxqy
     * @return
     */
    @PutMapping("/agree_three")
    public ResponseEntity<?> approveCarRequestThree(@RequestBody String approvalUrlWbxqy) {
        // 获取用车申请列表
        List<CarRequest> carRequests = carRequestService.getFullRequestByStatus("S2_A"); // 假设你有一个 service 获取数据
        for (CarRequest carRequest : carRequests) {
            // 设置用车申请相关属性
            carRequest.setStatusWbxqy("A"); // 三审-已通过
            carRequest.setApprovalUrlWbxqy(approvalUrlWbxqy);
            carRequest.setUpdateTimeWbxqy(LocalDateTime.now());
            carRequestService.updateById(carRequest);
            // 设置司机外出
            final User user = userService.getById(carRequest.getDriverIdWbxqy());
            user.setCarIdWbxqy(carRequest.getCarIdWbxqy());
            user.setStatusWbxqy("O");
            userService.updateById(user);
        }


        return ResponseEntity.ok("通过");
    }


    /**
     * 管理员拒绝用车申请
     *
     * @param carRequestDto
     * @return
     */
    @PutMapping("/reject")
    public ResponseEntity<?> rejectCarRequest(@RequestBody CarRequest carRequestDto) {
        CarRequest carRequest = carRequestService.getById(carRequestDto.getRequestIdWbxqy());
        if (carRequest == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("没有对应的用车申请");
        }
        carRequest.setRejectResonWbxqy(carRequestDto.getRejectResonWbxqy());
        carRequest.setStatusWbxqy("R"); // 已拒绝
        carRequest.setUpdateTimeWbxqy(LocalDateTime.now());
        carRequestService.updateById(carRequest);
        // 设置司机被占用
        if (carRequest.getCarIdWbxqy() != null) {
            final User user = userService.getById(carRequest.getDriverIdWbxqy());
            user.setCarIdWbxqy(carRequestDto.getCarIdWbxqy());
            user.setStatusWbxqy("O");
            userService.updateById(user);
        }
        return ResponseEntity.ok("拒绝");
    }

    /**
     * 行程报告详情
     *
     * @param carRequestId
     * @return
     */
    @GetMapping("/report-detail")
    public CarRequest reportDetail(@RequestParam Integer carRequestId) {
        CarRequest carRequest = carRequestService.getFullRequest(carRequestId);
        // 获取trip列表
        QueryWrapper<Trip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("request_id_wbxqy", carRequestId);
        List<Trip> tripList = tripService.list(queryWrapper);
        carRequest.setTripList(tripList);
        return carRequest;
    }

    @PutMapping("/addStatement")
    public String addStatement(@RequestBody Map<?, ?> map) {
        final CarRequest carRequest = carRequestService.getById((Integer) map.get("carRequestId"));
        carRequest.setStatementWbxqy((String) map.get("statement"));
        carRequest.setStatusWbxqy("B");
        carRequestService.updateById(carRequest);
        return "成功！";
    }

    private User getUser(String token) {
        final JSONObject tokenObj = (JSONObject) JSON.parse(JwtTokenUtil.getUsernameFromJWT(token));
        return userService.getById(tokenObj.get("userIdWbxqy").toString());
    }

    @GetMapping("/exportCarUse")
    public ResponseEntity<byte[]> exportCarUse(
            @RequestParam String status) throws IOException {
        // 获取用车申请列表
        List<CarRequest> carRequests = carRequestService.getFullRequestByStatus(status); // 假设你有一个 service 获取数据
        System.out.println(carRequests);

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("用车情况");

        // 1. 添加标题行（合并9列）
        Row titleRow = sheet.createRow(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));  // 合并单元格：标题行占9列
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("用车情况报告");
        titleCell.setCellStyle(createTitleCellStyle(workbook));  // 设置标题行样式

        // 2. 设置表头
        Row headerRow = sheet.createRow(1);  // 从第二行开始
        String[] headers = {"申请ID", "申请人", "申请事由", "车辆", "司机", "申请日期", "开始时间", "结束时间", "申请状态"};
        for (int i = 0; i < headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
        }

        // 填充数据
        int rowIndex = 2;  // 从第三行开始填充数据
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (CarRequest request : carRequests) {
            Row row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(request.getRequestIdWbxqy());
            row.createCell(1).setCellValue(request.getUser().getUsernameWbxqy());
            row.createCell(2).setCellValue(request.getPurposeWbxqy());
            row.createCell(3).setCellValue(request.getCar().getLicensePlateWbxqy());
            row.createCell(4).setCellValue(request.getDriver().getUsernameWbxqy());

            // 日期字段转换为可读格式
            row.createCell(5).setCellValue(formatDate(request.getRequestDateWbxqy().atStartOfDay(), dateFormatter));
            row.createCell(6).setCellValue(formatDate(request.getStartTimeWbxqy(), dateFormatter));
            row.createCell(7).setCellValue(formatDate(request.getEndTimeWbxqy(), dateFormatter));

            // 申请状态
            row.createCell(8).setCellValue("同意用车且确认分配无误");
        }

        // 3. 末尾添加合并单元格（审批人签名处）
        for (int i = 0; i < 1; i++) {
            Row footerRow = sheet.createRow(rowIndex++);
            sheet.addMergedRegion(new CellRangeAddress(rowIndex - 1, rowIndex - 1, 0, 7));  // 合并单元格
            Cell footerCell = footerRow.createCell(0);
            footerCell.setCellValue("审批人签名(盖章)处");
            footerCell.setCellStyle(createFooterCellStyle(workbook));  // 设置底部签名样式
        }

        // 输出到字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        byte[] data = baos.toByteArray();
        workbook.close();

        // 设置响应头，返回文件下载
        HttpHeaders headers_res = new HttpHeaders();
        headers_res.add("Content-Disposition", "attachment; filename=car_use_report.xlsx");
        return new ResponseEntity<>(data, headers_res, HttpStatus.OK);
    }

    // 日期格式化为可读形式
    private String formatDate(LocalDateTime dateTime, DateTimeFormatter formatter) {
        if (dateTime != null) {
            return dateTime.format(formatter);
        }
        return "";
    }

    // 创建标题行样式
    private CellStyle createTitleCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 14);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    // 创建底部签名行样式
    private CellStyle createFooterCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setItalic(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.RIGHT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }


}
